package cn.jekun.web.shop.service;

import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.NotNull;
import cn.jekun.component.core.bean.gen.RsAuth;
import cn.jekun.component.core.bean.gen.RsRole;
import cn.jekun.component.core.bean.gen.RsSystem;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.CoreAuthService;
import cn.jekun.component.core.service.gen.RsAuthService;
import cn.jekun.component.core.service.gen.RsRoleService;
import cn.jekun.web.shop.bean.Role;

/**
 * 角色管理服务层
 * @author hjz
 *
 */
@Service(RoleService.BEAN_NAME)
public class RoleService extends ShopBaseService{
	public static final String BEAN_NAME = "cn.jekun.web.shop.service.RoleService";

	@Override
	public String getNamespace() {
		return "ACTION_SHOP_ROLE";
	}
	
	@Resource(name=RsRoleService.BEAN_NAME)
	RsRoleService rsRoleService;
	
	@Resource(name=RsAuthService.BEAN_NAME)
	RsAuthService rsAuthService;
	
	@Resource(name=CoreAuthService.BEAN_NAME)
	CoreAuthService coreAuthService;
	
	//角色列表
	public List list(@RsRole.AnnoRoleName String roleName,@RsRole.AnnoCreateName String createName,@NotNull Page page) {
		Map formMap = new HashMap();
		formMap.put(RsRole.COL_ROLE_NAME, roleName);
		formMap.put(RsRole.COL_CREATE_NAME, createName);
		SqlUtis.prepareSql(formMap, 
				SqlUtis.getSQL(formMap, "a." + RsRole.COL_ROLE_NAME, Types.VARCHAR,SqlUtis.LIKE),
				SqlUtis.getSQL(formMap, "a." + RsRole.COL_CREATE_NAME, Types.VARCHAR, SqlUtis.EQ)
				);

		return this.rsRoleService.list(formMap, page);

	}
	
	/**
	 * 是否存在角色表
	 * @param roleId 角色代码
	 * @param createName 用户代码
	 * @return
	 */
	 @SuppressWarnings({ "unchecked", "rawtypes" })
	public boolean exists(@RsRole.AnnoRoleName String roleName,@RsUser.AnnoShopId String shopId){
		Map queryMap = new HashMap();
		queryMap.put(RsRole.COL_ROLE_NAME, roleName);
		queryMap.put(RsUser.COL_SHOP_ID, shopId);
		SqlUtis.prepareSql(queryMap
				,SqlUtis.getSQLRequired(queryMap, RsRole.COL_ROLE_NAME)
				,SqlUtis.getSQLRequired(queryMap, RsUser.COL_SHOP_ID)
				);
		return this.rsRoleService.exists(queryMap);
	 }

	 /**
	  * 根据角色ID获取角色详情
	  * @param roleId
	  * @return
	  */
	 public RsRole getRole(@RsRole.AnnoRoleId String roleId){
		 Map formMap = new HashMap();
		 formMap.put(RsRole.COL_ROLE_ID, roleId);
		 SqlUtis.prepareSql(formMap, ""
				 ,SqlUtis.getSQLRequired(formMap,"a."+RsRole.COL_ROLE_ID,Types.VARCHAR,SqlUtis.EQ)
				 );
		 return this.rsRoleService.one(formMap);
	 }

	 /**
	  * 更新角色
	  * @param role
	  */
	 @Transactional
	 public void updateRole(@NotNull(message="角色对象不为空")RsRole role){
		 Map formMap = new HashMap();
		 formMap.put(RsRole.COL_ROLE_ID, role.getRoleId());
		 SqlUtis.prepareSql(formMap,""
				 ,SqlUtis.getSQLRequired(formMap,"a."+RsRole.COL_ROLE_ID,Types.VARCHAR,SqlUtis.EQ)
				 );
		 formMap.put("rsRole", role);
		 this.rsRoleService.update(formMap);
	 }

	 /**
	  * 获取角色的权限
	  * @param roleId
	  * @param systemId
	  * @return
	  */
	 public List<HashMap> getAuthList(@RsUser.AnnoUserId String userId,@RsRole.AnnoRoleId String roleId,@RsSystem.AnnoSystemId String systemId){
		 Map formMap = new HashMap();
		 formMap.put("user_id",userId);
		 formMap.put("role_id",roleId);
		 formMap.put("system_Id", systemId);
		 
		 
		 return this.list(this.getStatementName("selectRoleAuth"),formMap);
	 }

	 /**
	  * 分配权限
	  * @param formMap
	  */
	 @SuppressWarnings("unchecked")
	 @Transactional
	 public void assignAuth(@RsRole.AnnoRoleId String roleId1,List<String> checkBoxAuth1,List<String> roleAuthId1) {
		 Map formMap = new HashMap();
		 formMap.put(RsRole.COL_ROLE_ID,roleId1);
		 formMap.put("checkBoxAuth", checkBoxAuth1);
		 formMap.put("roleAuthIdList",roleAuthId1);

		 String roleId = (String) formMap.get(RsRole.COL_ROLE_ID);
		 List<String> checkBoxAuth=(List<String>) formMap.get("checkBoxAuth");
		 if (StringUtils.isBlank(roleId)) {
			 throw new BusinessException("请先选择角色");
		 }
		 List<String> list=(List<String>) formMap.get("roleAuthIdList");

		 String roleAuthId="";

		 if(list!=null){

			 for(int i=0;i<list.size();i++){

				 if(list.size()==1 || i==list.size()-1){

					 roleAuthId+=list.get(i);
				 }else{

					 roleAuthId+=list.get(i)+",";
				 }

			 }
			 //先删除
			 //SqlUtis.prepareSql(formMap, "",SqlUtis.getSQLRequired(formMap,"a."+RsRole.COL_ROLE_ID,Types.VARCHAR,SqlUtis.EQ));
			 SqlUtis.prepareSql(formMap, " and a.ROLE_AUTH_ID in("+roleAuthId+")");
			 this.delete(getStatementName("deleteRoleAuth"), formMap);
			 formMap.remove(SqlUtis.WHERE_SQL);

		 }


		 //再增加
		 for(int i=0;i<checkBoxAuth.size();i++){

			 Map authMap = new HashMap();
			 authMap.put(RsRole.COL_ROLE_ID, roleId);
			 authMap.put(RsAuth.COL_AUTH_ID, checkBoxAuth.get(i));
			 this.insert(getStatementName("insertRoleAuth"), authMap);
		 }
	 }
	 
	 /**
	  * 获得该用户创建的角色
	  * @param userId
	  * @param createName
	  * @return
	  */
	 public List<Role> getAuthListByUserId(@RsUser.AnnoUserId String userId,@RsRole.AnnoCreateName String createName){
			Map formMap = new HashMap();
			formMap.put(RsUser.COL_USER_ID,userId);
			formMap.put(RsRole.COL_CREATE_NAME,createName);
			SqlUtis.prepareSql(formMap
					,SqlUtis.getSQLRequired(formMap, RsRole.COL_CREATE_NAME)
					);
			return this.list(this.getStatementName("selectRole"), formMap);
		}
	 
	 /**
		 * 用户分配角色
		 * @param formMap
		 */
		@Transactional
		public void assignRole(@RsUser.AnnoUserId String userId,@RsRole.AnnoRoleId String roleId) {
			Map formMap = new HashMap();
			formMap.put("USER_ID", userId);
			formMap.put("ROLE_ID", roleId);
		   //获取用户的ID
		   String USER_ID = (String) formMap.get(RsUser.COL_USER_ID);
		   	if (StringUtils.isBlank(USER_ID)) {
				throw new BusinessException("请先选择用户");
			}
		   //先删除已经分配了的角色
//		   	SqlUtis.prepareSql(formMap, ""
//					,SqlUtis.getSQLRequired(formMap,"a."+RsUser.COL_USER_ID,Types.VARCHAR,SqlUtis.EQ)
//				);
		   	formMap.put("user_id", userId);
		   	this.delete(getStatementName("deleteRoleUser"), formMap);
			formMap.remove(SqlUtis.WHERE_SQL);
		   
		   //分配角色给用户
			String ROLE_ID = (String) formMap.get(RsRole.COL_ROLE_ID);
			if (StringUtils.isBlank(ROLE_ID)) {
				return;
			}
			String[] role_ids = StringUtils.split(ROLE_ID,",");
			if(role_ids == null || role_ids.length == 0){
				return;
			}
			for (String role : role_ids) {
				if(StringUtils.isBlank(role)){
					continue;
				}
				Map roleMap = new HashMap();
				roleMap.put(RsRole.COL_ROLE_ID, role.trim());
				roleMap.put(RsUser.COL_USER_ID, USER_ID.trim());
				this.insert(getStatementName("insertRoleUser"), roleMap);
			 }

		 }
}
